<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.company_id" :placeholder="$t('table.company')" style="width:120px" clearable size="small" @change="handleFilterone(listQuery.company_id)">
        <el-option v-for="(item,index) in companylist " :key="index" :label="item.company" :value="item.id" />
      </el-select>
      <el-select v-model="listQuery.department_id" :placeholder="$t('table.department')" style="width:120px" clearable size="small" @change="handleFilter">
        <el-option v-for="(item,index) in department_list " :key="index" :label="item.department" :value="item.id" />
      </el-select>
      <el-input
        v-model="listQuery.person_id"
        :placeholder="$t('table.worker_id')"
        style="width: 200px;"
        size="small"
        clearable
        @change="handleFilter"
      />
      <el-input
        v-model="listQuery.name"
        :placeholder="$t('table.worker_name')"
        style="width: 200px;"
        size="small"
        clearable
        @change="handleFilter"
      />
      <div class="block">
        <el-date-picker
          v-model="listQuery.time"
          :start-placeholder="$t('table.start_time')"
          :end-placeholder="$t('table.end_time')"
          type="datetimerange"
          size="small"
          value-format="yyyy-MM-dd"
          range-separator="一"
          format="yyyy-MM-dd"
          @change="handleFiltertime"
        />
        <el-button type="primary" size="small" @click="getLists">{{
          $t("table.search")
        }}</el-button>

        <el-button type="primary" size="small" @click="getExcel">{{
          $t("table.export")
        }}</el-button>

        <!-- 弹出窗 -->
        <el-dialog
          :visible.sync="dialogVisible"
          :title="$t('table.normal_temperature_setting')"
          width="20%"
        >
          <div v-if="dialogVisible">
            <el-input v-model="editTemp.low_temp" style="width:100px" />
            <span v-if="$store.getters.is_centigrade == '1'"> ℃ —</span>
            <span v-if="$store.getters.is_centigrade == '2'"> ℉ —</span>
            <el-input v-model="editTemp.high_temp" style="width:100px" />
            <span v-if="$store.getters.is_centigrade == '1'"> ℃</span>
            <span v-if="$store.getters.is_centigrade == '2'"> ℉</span>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">{{
              $t("table.cancel")
            }}</el-button>
            <el-button type="primary" @click="Determine">{{
              $t("table.complete")
            }}</el-button>
          </span>
        </el-dialog>
        <el-button
          slot="reference"
          type="primary"
          size="small"
          @click="openSetting"
        >{{ $t("table.normal_temperature_setting") }}</el-button
        >
      </div>
    </div>
    <div>
      <el-table
        v-loading="listLoading"
        :data="list"
        :header-cell-style="{
          background: '#f2f2f2',
          color: '#606266',
          height: '10px',
          padding: '5px'
        }"
        :row-style="{ height: '40px', padding: '0px' }"
        :cell-style="{ padding: '0px' }"
        border
        fit
        highlight-current-row
        height="640px"
        width="80%"
      >
        <el-table-column :label="$t('table.worker_id')" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.person_id != '-1'">{{
              scope.row.person_id
            }}</span>
            <span v-else/>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.worker_name')" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.avatar')" align="center">
          <template slot-scope="scope">
            <img
              :src="base64Prefix + scope.row.now_img"
              style="width: auto;height: 80px;border: 0;"
            >
            <!-- <transition name="el-zoom-in-top">
              <div v-show="scope.row.person_id === listItemId" class="bigImg" @click="bigImg">
                <img :src="base64Prefix + scope.row.now_img">
              </div>
            </transition> -->
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.company')" align="center">
          <template slot-scope="scope">
            {{ scope.row.company }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.department')" align="center">
          <template slot-scope="scope">
            {{ scope.row.department }}
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('table.date_time')"
          class-name="status-col"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.pass_ts }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.temperature')" align="center">
          <template slot-scope="scope">
            {{ scope.row.mapping_temp | toTemp }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.temperature_status')" align="center">
          <template slot-scope="scope">
            <!-- <div v-if="$store.getters.is_centigrade == 1"> -->
            <div>
              <span v-if="scope.row.mapping_temp >= Temperature.high_temp">
                <el-tag type="danger" style="font-weight: 800;font-size:14px">
                  {{ Fever }}
                </el-tag>
              </span>
              <span
                v-else-if="
                  scope.row.mapping_temp <= Temperature.high_temp &&
                    scope.row.mapping_temp > Temperature.low_temp
                "
              >
                <el-tag type="success">
                  {{ Normal }}
                </el-tag>
              </span>
              <span v-else>
                <el-tag type="info" style="font-weight: 800;font-size:14px">
                  {{ TooLow }}</el-tag
                  >
              </span>
            </div>
            <!-- <div v-if="$store.getters.is_centigrade == 2">
              <span v-if="switchHTemp(scope.row.mapping_temp) >= switchHTemp(Temperature.high_temp)">
                <el-tag type="danger">
                  {{ Fever }}
                </el-tag>
              </span>
              <span
                v-else-if="
                switchHTemp(scope.row.mapping_temp) <= switchHTemp(Temperature.high_temp) &&switchHTemp(scope.row.mapping_temp) > switchHTemp(Temperature.low_temp)">
                <el-tag type="success">
                  {{ Normal }}
                </el-tag>
              </span>
              <span v-else>
                <el-tag type="info"> {{scope.row.mapping_temp}}{{ TooLow }}</el-tag>
              </span>
            </div> -->
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="current_page"
          :page-sizes="[50, 100, 200]"
          :page-size="per_page"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>
<script>
import store from '@/store'
import { parseTime } from '@/utils/index'
import {
  temp_get_list,
  temp_get_select,
  config_get_list,
  config_edit
} from '@/api/BodyTemperature/BodyTemperature'
import {
  get_select
} from '@/api/organization_manage/organization_manage'
import { getTemperature, switchTemperature } from '@/api/index/index'
import {
  department_get_select
} from '@/api/user_manage/user_manage'
export default {
  data() {
    return {
      TooLow: this.$t('table.temperature_low'),
      Fever: this.$t('table.temperature_hight'),
      Normal: this.$t('table.normal'),
      Minimum: null,
      Highest: null,
      dialogVisible: false,
      list: null,
      listLoading: true,
      total: null,
      current_page: null,
      last_page: null,
      per_page: null,
      base64Prefix: 'data:image/jpg;base64,',
      listItemId: null,
      companylist: null,
      Temperature: {
        low_temp: 0,
        height_temp: 0
      },
      timeout: null,
      department_list: null,
      editTemp: {},
      listQuery: {
        company_id: undefined,
        department_id: undefined,
        endTime: undefined,
        beginTime: undefined,
        name: undefined,
        time: [],
        person_id: undefined,
        page: 1,
        pagesize: 50
      },
      value1: '',
      value2: '',
      // 导出数据
      export: []
    }
  },

  created() {
    this.getListspos()
    const timestamp = new Date().getTime()
    this.listQuery.beginTime = this.time(timestamp - 2592000000)
    this.listQuery.endTime = this.time(timestamp)
    this.listQuery.time[0] = this.listQuery.beginTime
    this.listQuery.time[1] = this.listQuery.endTime
    console.log(this.time(timestamp), 'tttttttttttttttttt')
  },
  mounted() {
    this.timeout = setInterval(() => {
      console.log('执行了temperture')
      this.getLists()
    }, 3000)
  },
  beforeDestroy() {
    // 清除定时器
    clearInterval(this.timeout)
    console.log('beforeDestroy')
  },
  methods: {
    time(time) {
      var date = new Date(time + 8 * 3600 * 1000)
      return date
        .toJSON()
        .substr(0, 10)
        .replace('T', ' ')
        .replace(/-/g, '-')
    },
    openSetting() {
      this.dialogVisible = true
      // 获取正常体温
      getTemperature(store.getters.token, { id: 1 }).then(res => {
        console.log(res.data.data)
        if(!res.data.data){
          return
        }
        this.editTemp = res.data.data
        if (this.$store.getters.is_centigrade == '2') {
          this.editTemp.low_temp = this.switchCTemp(this.editTemp.low_temp)
          this.editTemp.high_temp = this.switchCTemp(this.editTemp.high_temp)
          this.Temperature.height_temp=this.editTemp.high_temp
          this.Temperature.low_temp=this.editTemp.low_temp
        }
        console.log(this.editTemp.temp_range2, 'this.editTemp.temp_range2')
        console.log(this.editTemp, 'this,temperature')
      })
    },

    // 获取展示列表数据
    getListspos() {
      this.listLoading = true
      temp_get_list(store.getters.token, this.listQuery).then(res => {
        this.list = res.data.list.data
        this.current_page = res.data.list.current_page
        this.per_page = res.data.list.per_page
        this.last_page = res.data.list.last_page
        this.total = res.data.list.total
        this.listLoading = false
      })

      // 获取正常体温
      getTemperature(store.getters.token, { id: 1 }).then(res => {
        if(res.data.data ){
          this.Temperature = res.data.data
        }
        // if (this.$store.getters.is_centigrade == "2") {
        //   this.Temperature.low_temp = this.switchCTemp(
        //     this.Temperature.low_temp
        //   );
        //   this.Temperature.high_temp = this.switchCTemp(
        //     this.Temperature.high_temp
        //   );
        // }
        console.log(this.Temperature, 'this,temperature')
      })
      // 获取公司数据
      get_select(store.getters.token).then((res) => {
        this.companylist = res.data.list
      })
    },
    // 华氏度转为摄氏度
    switchCTemp(ctemp) {
      if(ctemp){
        return ((ctemp * 9) / 5 + 32).toFixed(2)
      }else{
        return null
      }
    },
    // 摄氏度转为华氏度
    switchHTemp(htemp) {
      return ((5 / 9) * (htemp - 32)).toFixed(2)
    },
    getLists() {
      temp_get_list(store.getters.token, this.listQuery).then(res => {
        this.list = res.data.list.data
        this.current_page = res.data.list.current_page
        this.per_page = res.data.list.per_page
        this.last_page = res.data.list.last_page
        this.total = res.data.list.total
        this.listLoading = false
      })
      // 获取正常体温
      getTemperature(store.getters.token, { id: 1 }).then(res => {
        this.Temperature = res.data.data
        // if (this.$store.getters.is_centigrade == "2") {
        //   this.Temperature.low_temp = this.switchCTemp(
        //     this.Temperature.low_temp
        //   );
        //   this.Temperature.high_temp = this.switchCTemp(
        //     this.Temperature.high_temp
        //   );
        // }
        console.log(this.Temperature, 'this,temperature')
      })
      // 获取公司数据
      get_select(store.getters.token).then((res) => {
        this.companylist = res.data.list
      })
    },

    // 分页相关方法
    handleFilter() {
      this.listQuery.page = 1
      this.getLists()
    },
    handleFilterone(val) {
      this.listQuery.page = 1
      this.getLists()
      department_get_select(store.getters.token, { company_id: val }).then(
        (res) => {
          this.department_list = res.data.list
          console.log(this.department_list, 'this,department_list')
          console.log(res, 'res.data.list')
        }
      )
    },
    handleFiltertime(val) {
      this.listQuery.beginTime = val[0]
      this.listQuery.endTime = val[1]
      this.getLists()
    },
    handleSizeChange(val) {
      this.listQuery.pagesize = val
      this.getLists()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getLists()
    },

    // 导出表
    getExcel() {
      const date = new Date() // 时间戳为10位需乘1000，为13位则不用
      const Y = date.getFullYear() // 年
      const M =
        date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1 // 月
      const D =
        date.getDate() < 10 ? '0' + date.getDate() + '' : date.getDate()
      const date_time = Y + '-' + M + '-' + D

      temp_get_select(store.getters.token, this.export)
        .then(res => {
          this.export = res.data.list.data
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = [
              this.$t('table.worker_id'),
              this.$t('table.worker_name'),
              this.$t('table.company'),
              this.$t('table.department'),
              this.$t('table.date'),
              this.$t('table.temperature'),
              this.$t('table.temperature_status')
            ]
            const filterVal = [
              'person_id',
              'name',
              'company',
              'department',
              'pass_ts',
              'mapping_temp',
              'temperature_status'
            ]
            const list = res.data.list.data
            const data = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: this.$t('table.temperature_report') + ' ' + date_time,
              autoWidth: true,
              bookType: 'xlsx'
            })
          })
        })
        .catch(err => {
          console.log('导出失败', err)
          this.$message.error('ERROR')
        })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          // if(this.$store.getters.is_centigrade == "1"){
          //   console.log(this.switchCTemp(this.editTemp.high_temp),'this.switchCTemp(this.editTemp.high_temp)')
          //   v.mapping_temp =  v.mapping_temp
          // }else{
          //   console.log(this.switchHTemp,'2222222222')
          //   v.mapping_temp = this.switchHTemp(v.mapping_temp.htemp);
          // }
          if (j == 'mapping_temp') {
            if (this.$store.getters.is_centigrade == '2') {
              return this.switchCTemp(v[j]) + ' ℉'
            } else {
              return v[j] + ' ℃'
            }
          }
          if (j == 'person_id') {
            if (v.person_id == '-1') {
              return v.person_id == ''
            } else {
              return v.person_id
            }
          }
          if (j === 'temperature_status') {
            if (v.mapping_temp >= this.Temperature.high_temp) {
              return this.Fever
            } else if (
              v.mapping_temp <= this.Temperature.high_temp &&
              v.mapping_temp > this.Temperature.low_temp
            ) {
              return this.Normal
            } else {
              return this.TooLow
            }
          } else {
            return v[j]
          }
        })
      )
    },
    bigImg(id) {
      console.log(id, 'id')
      if (id > 0) {
        this.listItemId = id
      } else {
        this.listItemId = null
      }
    },
    // Determine(){
    //   // this.dialogVisible = false
    //   // var data = { Minimum: this.Minimum , Highest: this.Highest }
    //   // window.localStorage.setItem(STORAGE_KEY, JSON.stringify(data))
    //   // console.log(this.Minimum,'this.minimum',this.Highest,'this.highest')
    //   // localStorage.getItem('Minimum')
    //   // // console.log(localStorage.getItem('Minimum'),'localStorage.getItem')
    //   // console.log(localStorage.getItem(STORAGE_KEY),'ssssssssssss');
    //   // this.Minimum = JSON.parse(localStorage.getItem(STORAGE_KEY)).Minimum;
    //   // this.Highest = JSON.parse(localStorage.getItem(STORAGE_KEY)).Highest;
    //   // console.log(this.Minimum,'mmmmmmmmmmmmmmmm',this.Highest);
    //   // // this.Highest = JSON.parse(localStorage.getItem(data.Highest))
    // },
    Determine() {
      if (this.$store.getters.is_centigrade == '2') {
        this.editTemp.low_temp = this.switchHTemp(this.editTemp.low_temp)
        this.editTemp.high_temp = this.switchHTemp(this.editTemp.high_temp)
      }
      switchTemperature(store.getters.token, this.editTemp).then(res => {
        if (res.data.status) {
          this.$message.success(this.$t('table.edit_complete'))
          this.getLists()
          this.dialogVisible = false
        } else if (res.data.msg == '更新据失败！') {
          this.dialogVisible = false
        } else {
          this.$message.error(this.$t('table.edit_fail'))
        }
      })
    }
  }
}
</script>
<style scoped>
.block {
  display: inline-block;
  margin-left: 20px;
}

.app-container {
  border: #eee solid 10px;
}

.pagination-container {
  margin-top: 25px;
  font-weight: 800;
}
.bigImg {
  min-width: 100%;
  min-height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999999;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  /*transition:1s;*/
}
.bigImg img {
  max-width: 650px;
  min-width: 235px;
}
</style>
